<template>
  <div class="m-view-quarterlyReconciliation m-window" ref="elementId">
    <!-- 搜索条件 -->
    <div class="m-condition" v-show="!componentsShow">
      <div class="flex hor-flex-end mb-10">
        <el-button type="primary" @click="search('init')" :disabled="searchBtnDisabled"
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="createRecon"
          v-if="isInnerUser"
          >新增季度对账函</el-button
        >
        <el-button type="primary" @click="edit"
          >编辑</el-button
        >
        <el-button type="primary" @click="print" v-if="isInnerUser"
          >打印</el-button
        >
        <el-button
          type="primary"
          @click="deleteRows"
          :disabled="deleteBtnDisabled"
          v-if="isInnerUser"
          >删除</el-button
        >
        <el-button
          type="primary"
          @click="
            () => {
              download();
            }
          "
          v-if="isInnerUser"
          >下载附件</el-button
        >
      </div>
      <el-row :gutter="10">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="60px"
          :inline-message="true"
          label-position="left"
        >
          <!-- 公司  -->
          <el-col :span="6">
            <el-form-item label="公司" class="rightItem">
              <el-select
                value-key="id"
                v-model="ruleForm.selCompanyCode"
                placeholder="请选择公司"
                @change="companyChange"
                ref="content"
                filterable
                clearable
              >
                <el-option
                  v-for="item in comOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 供应商  -->
          <el-col :span="6" v-if="isInnerUser">
            <el-form-item label="供应商" class="rightItem">
              <supplier
                :layout="layout"
                :supplierInfo.sync="ruleForm.supplier"
              />
            </el-form-item>
          </el-col>

          <!-- 审核日期 -->
          <el-col :span="isInnerUser ? 5 : 6">
            <el-form-item label="期间" class="rightItem">
              <el-date-picker
                v-model="ruleForm.queryDateStart"
                type="date"
                value-format="yyyy-MM-dd"
                clearable
                :editable="false"
                :picker-options="po1"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="isInnerUser ? 3 : 6">
            <el-date-picker
              v-model="ruleForm.queryDateEnd"
              type="date"
              value-format="yyyy-MM-dd"
              clearable
              :editable="false"
              :picker-options="po2"
            ></el-date-picker>
          </el-col>

          <!-- 状态 -->
          <el-col :span="isInnerUser ? 4 : 6">
            <el-form-item label="状态" class="rightItem">
              <el-select
                v-model="ruleForm.state"
                @change="search('init')"
                clearable
              >
                <el-option
                  v-for="item in stateList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!-- aggrid -->
    <div class="m-agTable m-bottom m-top2" v-show="!componentsShow">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="tableData"
        rowSelection="multiple"
        v-loading="loading"
      ></ag-grid-vue>
    </div>
    <!-- 页码 -->
    <div class="m-page" v-show="!componentsShow">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handleCurrentChange"
        @next-click="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <createReconciliation v-if="componentsShow" class="m-window" @back="back" />

    <!--弹框 -->
    <el-dialog
      title="查看季度对账函"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="m-quaterly-reconcliliation-dia"
    >
      <el-form
        :model="dialogForm"
        ref="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-form-item class="rightItem" label="公司">
          <el-input v-model="dialogForm.companyName" disabled></el-input>
        </el-form-item>
        <el-form-item class="rightItem" label="供应商">
          <el-input v-model="dialogForm.supplierName" disabled></el-input>
        </el-form-item>
        <el-form-item label="截止日期" class="rightItem">
          <el-date-picker
            v-model="dialogForm.deadline"
            type="date"
            disabled
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="rightItem" label="上月欠款">
          <el-input v-model="dialogForm.lastMonthDebt" disabled></el-input>
        </el-form-item>
        <el-form-item class="rightItem" label="当月借款发生数">
          <el-input v-model="dialogForm.thisMonthDebit" disabled></el-input>
        </el-form-item>
        <el-form-item class="rightItem" label="当月贷款发生数">
          <el-input v-model="dialogForm.thisMonthCredit" disabled></el-input>
        </el-form-item>
        <el-form-item class="rightItem" label="截止日期欠款余额">
          <el-input v-model="dialogForm.deadlineDebtsBalance" disabled></el-input>
        </el-form-item>
        <el-form-item class="rightItem" label="采购方附件">
          <v-attach
            :acceptFile="allAcceptFile"
            :uploadMaxCount="uploadMaxCount"
            ref="vAttach"
            :value.sync="purchaserAttachList"
            :isShowUploader="isInnerUser"
          />
        </el-form-item>
        <el-form-item class="rightItem" label="供应方附件">
          <v-attach
            :acceptFile="allAcceptFile"
            :uploadMaxCount="uploadMaxCount"
            ref="vAttach"
            :value.sync="supplierAttachList"
            :isShowUploader="!isInnerUser"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="sendBtnDisabled" @click="send">{{
          isInnerUser ? "发送" : "确认"
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style lang="less">
.m-view-quarterlyReconciliation {
  .m-quaterly-reconcliliation-dia {
    .el-dialog__body {
      height: 400px;
      overflow: auto;
    }
  }
}
</style>

<script>
import _Api from "@/api";
import createReconciliation from "./common/createReconciliation";
import VAttach from "@/components/vAttach";

import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import supplier from "@/components/supplier";
import serviceTime from "@/public/serverTime.js";
import constant from "@/public/constant";
import Msg from "@/public/message.js";
import apienv from "@/api/env";
import fileStream from "@/public/fileStream.js";
import { startPrint } from "lesso-common/webprint";
import downLoadFileFunc from "@/public/downLoadFile";

const ENV = apienv[constant.appenv];

export default {
  data() {
    return {
      //   文件上传地址
      baseUrl: ENV.srm + "uploadFastdfs/",
      userInfo: {
        userName: this.$global.user.employeeName,
        userId: this.$global.user.id,
        groupName: "SRM"
      },
      layout: {
        companyCode: ""
      },
      ruleForm: {
        supplier: {},
        selCompanyCode: {},
        queryDateStart: '',
        queryDateEnd: '',
      },
      dialogForm: {},
      comOptions: [], // 公司列表
      stateList: [
        { label: "待发送", value: "0" },
        { label: "待确认", value: "1" },
        { label: "已确认", value: "2" }

      ],
      searchBtnDisabled: false,
      sendBtnDisabled: false,
      deleteBtnDisabled: false, // 删除按钮
      po1: {
        disabledDate: this.disabledDate1
      },
      po2: {
        disabledDate: this.disabledDate2
      },
      currentPage: 1,
      pageSize: 30,
      total: 0,
      loading: false,
      tableData: [],
      componentsShow: false,
      dialogVisible: false,
      queryParams: {},
      // 用户类型,4为供应商，1为内部用户
      isInnerUser: this.$global.user.userTypeId == 1,
      purchaserAttachList: [], // 采购方附件列表
      supplierAttachList: [], // 供应方附件列表
      uploadMaxCount: 1,
      allAcceptFile: constant.accept_file
    };
  },
  methods: {
    // 校验表单
    validate() {
      // 内部用户需校验采购方是否有上传附件
      const ATTACHLIST = this.isInnerUser
        ? this.purchaserAttachList
        : this.supplierAttachList;
      const TIPS = {
        unUnloadFile: `请在${
          this.isInnerUser ? "采购方" : "供应方"
        }附件一栏上传附件`,
        fileUploading: `附件还在上传中，请稍等`
      };
      if (!ATTACHLIST.length) {
        this.$alert(TIPS.unUnloadFile, {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        });
        return false;
      } else {
        for (let { viewPath } of ATTACHLIST) {
          if (!viewPath) {
            this.$alert(TIPS.fileUploading, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertPrompt"
            });
            return false;
          }
        }
      }
      return true;
    },
    validateTable(optType) {
      let selectRow = this.gridOptions.api.getSelectedRows();
      const map = {
        delete: "删除",
        edit: "编辑",
        print: "打印",
        download: "下载"
      };
      if (!selectRow.length) {
        this.$alert(`请选择要${map[optType]}的数据`, {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        });
        return false;
      }
      if(['edit', 'download', 'print'].indexOf(optType) != -1) {
        if (selectRow.length > 1) {
          this.$alert(`只能选择一行数据`, {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertPrompt"
          });
          return false;
        }
      }
       //编辑操作不能编辑已确认的对账函
      if (optType === "edit") {
        for (let { state } of selectRow) {
          if (state == "2") {
            this.$alert(`只能编辑待发送和待确认状态下的数据`, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertPrompt"
            });
            return false;
          }
        }
      }
      // 删除操作只能删除待发送状态下的数据
      if (optType === "delete") {
        for (let { state } of selectRow) {
          if (state != "0") {
            this.$alert(`只能删除待发送状态下的数据`, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertPrompt"
            });
            return false;
          }
        }
      }
      // 下载附件操作只能下载待确认或者已确认的单据
      if (optType === "download") {
        for (let { state } of selectRow) {
          if (state == "0") {
            this.$alert(`只能下载待确认和已确认状态下的数据`, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertPrompt"
            });
            return false;
          }
        }
      }
      return true;
    },
    // 打印数据
    print() {
      if (!this.validateTable("print")) return;
     
      if (constant.userAgent == "web") {
         
        this.printWeb();
      } else {
        this.printPc();
      }
    },
    printPc() {
     
      let templateName = 'quarLetter';
      let rowsData = this.gridOptions.api.getSelectedRows();
      let lists = [];
      for(let row of rowsData) {
        lists.push({
          companyName: row.companyName,
          remark: row.remark,
          deadline: row.deadline,
          supplierName: row.supplierName,
          accountCode: row.accountCode,
          contact: row.contact,
          email: row.email,
          fax: row.fax,
          address: row.address,
          tel: row.tel,
          lend: row.lend,
          borrow: row.borrow,
          letterCode: row.letterCode
        })
      }
      
      if (constant.printType == "local") {
        ipcRenderer.send("IPCR_M_PRINTLOCAL", {
          type: templateName,
          rows: rowsData,
          optype: "pr",
          isdefaultp: 1 //控制是否直接打印,0为选择打印、1为直接打印
        });
      } else {
        
        fileStream
          .getFileInfo(templateName)
          .then(data => {
            
            ipcRenderer.send("IPCR_M_PRINT", {
              type: templateName,
              rows: lists,
              groupName: data.groupName,
              optype: "pr",
              url: data.url,
              isdefaultp: 1 //控制是否直接打印,0为选择打印、1为直接打印
            });
          })
          .catch(err => {
            this.$alert(err, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            });
          });
      }
    },
    printWeb() {
      let templateName = "quarLetter";
      let selectRow = this.gridOptions.api.getSelectedRows();
      let ids = ''
      for(let {id} of selectRow) {
        ids += id + ','
      }
      ids = ids.substring(0, ids.length - 1)
      fileStream
        .getFileInfo(templateName)
        .then(data => {
          startPrint({
            basicUrl: ENV["srm"], //权限接口地址
            reportUrl: `${ENV["srm"]}download2?viewPath=${data.url}&groupName=${data.groupName}`, //打印模板地址
            dataUrl: `quarterlyStatementLetter/printLetter/${ids}`, //数据接口地址
            printType: "preview", // 打印方式print直接打印，preview先预览
            params: {
							'token': '',
						},
          });
        })
        .catch(err => {
          this.$alert(err, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        });
    },
    // 删除行数据
    deleteRows() {
      if (!this.validateTable("delete")) return;
      this.loading = true;
      this.delQuarterRecord = true;
      let id = "";
      let selectRow = this.gridOptions.api.getSelectedRows();
      for (let i = 0; i < selectRow.length; i++) {
        if (selectRow[i].id) {
          id += selectRow[i].id + ",";
        }
      }
      id = id.substr(0, id.length - 1);
      _Api
        .delQuarterRecord(id)
        .then(({ data: {code, rows, total, info} }) => {
          this.loading = false;
          this.delQuarterRecord = false;
          // 删除成功刷新列表
          if (code === 1) {
            Msg.showSuccessMsg("删除成功");
            this.search("init")
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
          this.loading = false;
          this.delQuarterRecord = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    // 下载附件
    download(rowData) {
      let selectRow = null;
      if (!rowData) {
        if (!this.validateTable("download")) return;
        selectRow = this.gridOptions.api.getSelectedRows()[0];
      } else {
        selectRow = rowData;
      }
      this.downloadFile(selectRow);
    },
    downloadFile(rowData) {
      if(rowData.state == 0) return;
      // 待确认
      let attachObj = null
      if(rowData.state == 1) {
        attachObj = rowData.companyAttachment || {}
      } else {
        attachObj = rowData.supplierAttachment || {}
      }
      const {url: viewPath, name: fileName} = attachObj;
      if (!viewPath) return;
      var obj = {
        viewPath,
        fileName
      };
      obj.groupName = "TEST";
      obj.fileName = "";
      if (viewPath.indexOf("SRM") > -1) {
        obj.groupName = "SRM";
      } else if (viewPath.indexOf("SIGN") > -1) {
        obj.groupName = "SIGN";
      } else if (viewPath.indexOf("TEST") > -1) {
        obj.groupName = "TEST";
      }
      downLoadFileFunc(obj, fileName);
    },
    send() {
      if (!this.validate()) return;
      let [companyAttach = {}] = this.purchaserAttachList;
      let [supplierAttach = {}] = this.supplierAttachList
      const params = {
        companyAttachment: {
          size: companyAttach.length,           // 附件大小
          url: companyAttach.viewPath,            // 附件地址
          md5: companyAttach.md5,            // 附件md5
          name: companyAttach.name,            // 附件名
        },
        supplierAttachment: {
          size: supplierAttach.length,           // 附件大小
          url: supplierAttach.viewPath,            // 附件地址
          md5: supplierAttach.md5,            // 附件md5
          name: supplierAttach.name,            // 附件名
        },
        id: this.dialogForm.id
      }
      _Api
        .sendQuarterLetter(params)
        .then(({ data: {code, info} }) => {
          this.loading = false;
          this.sendBtnDisabled = false;
          if (code === 1) {
            this.dialogVisible = false;
              Msg.showSuccessMsg(info);
              this.search();
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
          this.loading = false;
          this.sendBtnDisabled = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    // 创建季度函
    createRecon() {
      this.componentsShow = true;
    },
    // 编辑季度函
    edit() {
      if (!this.validateTable("edit")) return;
      let selectRow = this.gridOptions.api.getSelectedRows();
      this.dialogForm = selectRow[0];
      const {url: viewPath, size: length, md5,name} = this.dialogForm.companyAttachment || {};
      const {url: viewPath1, size: length1, md5: md51,name: name1} = this.dialogForm.supplierAttachment || {};
      if(viewPath) {
        this.purchaserAttachList = [{
          viewPath,
          length,
          md5,
          name
        }];
      }
      if(viewPath1) {
        this.supplierAttachList = [{
          viewPath: viewPath1,
          length: length1,
          md5: md51,
          name: name1
        }];
      }
      this.dialogVisible = true;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.search();
    },
    // 查询
    search(type, arg = {}) {
      if (type === "init") {
        this.currentPage = 1;
      }
      let params = {
        current: this.currentPage,
        pageSize: this.pageSize,
        companyCode: this.ruleForm.selCompanyCode.companyCode,
        // 内部用户，自己选择供应商，外部用户，默认供应商
        supplierCode: this.isInnerUser
          ? this.ruleForm.supplier.supplierCode
          : (constant.supplierData || {}).supplierCode,
        ...this.ruleForm,
        queryDateStart: this.ruleForm.queryDateStart
          ? `${this.ruleForm.queryDateStart} 00:00:00.0`
          : "",
        queryDateEnd: this.ruleForm.queryDateEnd
          ? `${this.ruleForm.queryDateEnd} 00:00:00.0`
          : "",
        ...arg
      };
      this.loading = true;
      this.tableData = [];
      this.searchBtnDisabled = true;
      _Api
        .queryQuarterPage(params)
        .then(({ data: {code, rows, total, info} }) => {
          this.loading = false;
          this.searchBtnDisabled = false;
          if (code === 1) {
              this.total = total;
              this.tableData = rows;
          } else {
            Msg.showErrorMsg(info);
          }
        })
        .catch(err => {
          this.loading = false;
          this.searchBtnDisabled = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    companyChange(item) {
      this.layout.companyCode = item.companyCode;
      this.layout.auth = true;
      this.search("init");
    },
    disabledDate1(time) {
      if (this.ruleForm.queryDateEnd)
        return time.getTime() > new Date(this.ruleForm.queryDateEnd).getTime();
    },
    disabledDate2(time) {
      if (this.ruleForm.queryDateStart)
        return (
          time.getTime() <
          new Date(this.ruleForm.queryDateStart).getTime() - 3600 * 1000 * 24
        );
    },
    // isRfreshTable  是否刷新列表数据
    back(isRfreshTable) {
      this.componentsShow = false;
      if(isRfreshTable) {
        this.search('init', {
          companyCode: undefined,
          queryDateEnd: '',
          queryDateStart: '',
          state: '',
          supplierCode: undefined
        })
      }
    },
    findLabel(val, arr) {
      for (let { label, value } of arr) {
        if (value == val) {
          return label;
        }
      }
    },
    initData() {
      //查询公司列表
      var obj = {};
      if (constant.user.userTypeId == 4) {
        obj.account = constant.user.userName;
        obj.userType = 2;
      } else {
        obj.account = constant.user.oaNum;
        obj.userType = 1;
      }
      _Api
        .getAuthInfo(obj)
        .then((response) => {
          var data = response.data;
          if (data.code == "1") {
            this.comOptions = data.rows.myMstCompany;
            //默认公司
            if (constant.user.userTypeId != 4) {
              //找登录人所在公司的条目
              for (var i = 0; i < this.comOptions.length; i++) {
                if (this.comOptions[i].companyCode == constant.user.bukrs) {
                  this.ruleForm.selCompanyCode = this.comOptions[i];
                  break;
                }
              }
            }
            this.layout.companyCode = this.ruleForm.selCompanyCode.companyCode;
            this.layout.auth = true;
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
          this.comOptions = [];
        });
    },
    initControl() {
      //默认日期范围 三个月
      serviceTime.getServiceTime().then(serviceTime => {
       if (serviceTime) {
          this.ruleForm.queryDateStart = new Date(
            serviceTime.getTime() - 30 * 24 * 3600 * 1000
          ).Format("yyyy-MM-dd");
          this.ruleForm.queryDateEnd = serviceTime.Format("yyyy-MM-dd");
        }
      });
    }
  },
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this
        },
        localeText: localeText,
        suppressRowClickSelection: true,
        enableColResize: true,
      },
      gridOptions({
        singleSelection: true,
      }),
    );
    this.columnDefs = [
      {
        headerName: "公司",
        checkboxSelection: true,
        headerCheckboxSelection: true,
        field: "companyName",
        width: 150
      },
      {
        headerName: "截止日期",
        field: "deadline",
        width: 150
      },
      {
        headerName: "创建日期",
        field: "createDate",
        width: 150
      },
      {
        headerName: "创建人",
        field: "creator",
        width: 150
      },
      {
        headerName: "修改日期",
        field: "modifyDate",
        width: 150
      },
      {
        headerName: "修改人",
        field: "modifier",
        width: 150
      },
      {
        headerName: "状态",
        field: "state",
        width: 150,
        cellRenderer: (params) => {
          return this.findLabel(params.value, this.stateList);
        }
      },
      {
        headerName: "最终附件",
        width: 150,
        cellRendererFramework: "OperateComponent",
        pinned: "right"
      }
    ];
    if (this.isInnerUser) {
      this.columnDefs.splice(1, 0, {
        headerName: "供应商",
        field: "supplierName",
        width: 150
      });
    }
  },
  components: {
    OperateComponent: {
      template: `
            <div style="cursor: pointer" class="rendererClass" @click="download">
              下载
            </div>
          `,
      methods: {
        download() {
          this.params.context.componentParent.download(this.params.node.data);
        }
      }
    },
    createReconciliation,
    supplier,
    VAttach
  },
  mounted() {
    // 初始化控件
    this.initControl();
    //初始化数据源
    this.initData();
  }
};
</script>